import socket
import binascii
from checkin import app
from flask import request

@app.route("/wol") # 路由
def wol():
    mac = request.args.get('mac')
    wakeup(mac)
    return f'Hello, {mac}!'

def wakeup(mac_address):
    # 构建魔术包
    magic_packet = "FF" * 6 + mac_address.replace("-", "") * 16

    # 将十六进制字符串转换为二进制数据
    magic_packet = binascii.unhexlify(magic_packet)

    # 创建UDP套接字
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

    # 发送魔术包到目标计算机的IP地址和端口
    target_ip = "192.168.3.255"  # 目标计算机的IP地址
    target_port = 9  # 通常是 7 或 9
    udp_socket.sendto(magic_packet, (target_ip, target_port))
    # 关闭套接字
    udp_socket.close()